import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs-extra'
import simpleGit from 'simple-git'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 配置项
const TARGET_BRANCH = 'production'
const REMOTE = 'https://gitee.com/liuweiyibai/electron-smallest-updater.git' // 例如 git@github.com:user/repo.git
const PROJECT_ROOT = __dirname
const DIST_DIR = path.join(PROJECT_ROOT, 'dist')
const PACKAGE_JSON = path.join(PROJECT_ROOT, 'package.json')
const TEMP_DIR = path.join(PROJECT_ROOT, '.deploy-temp')

async function deploy() {
  // 清理并准备临时目录
  await fs.remove(TEMP_DIR)
  await fs.mkdirp(TEMP_DIR)

  // 复制 dist 目录（整个目录）
  await fs.copy(DIST_DIR, path.join(TEMP_DIR, 'dist'))
  console.log('✅ dist 目录已复制')

  // 复制 package.json
  await fs.copy(PACKAGE_JSON, path.join(TEMP_DIR, 'package.json'))
  console.log('✅ package.json 已复制')

  // 初始化 Git 仓库
  const git = simpleGit(TEMP_DIR)
  await git.init()
  await git.addRemote('origin', REMOTE)
  await git.add('.')
  await git.commit('deploy: 发布 dist 和 package.json 到 ' + TARGET_BRANCH)
  console.log('✅ Git commit 完成')

  // 强制推送
  await git.push(['-f', 'origin', `HEAD:${TARGET_BRANCH}`])
  console.log(`🚀 已成功推送到 ${TARGET_BRANCH} 分支`)
}

deploy().catch((err) => {
  console.error('❌ 部署失败:', err)
})
